import requests
import asyncio
import json
from utils import *
import logging
import pymysql
_logger = logging.getLogger(__name__)


# 本地模拟连接
URL = 'http://127.0.0.1:3000/dcs/upload/spindle_status'

mysql_conn = pymysql.connect("localhost","root","root","dcs" )


def task_push_spindles_status_to_cloud(loop):
    """ 将本地 mysql数据库 的数据 push 到 阿里云 postgres """

    print_threading_info()
    # 1 先实现上传
    # 2 然后改进：实现过滤后再上传
    cursor = mysql_conn.cursor()
    cursor.execute("SELECT spindle_no,machine_ip, machine_code, status, speed from spindle_status")
    spindle_status = cursor.fetchall()
    data = json.dumps({
        "spindle_status": spindle_status
    })
    _logger.debug(data)
    try:
        #_logger.debug(datetime.now())
        requests.post(URL, data=data)
        #_logger.debug(datetime.now())
    except Exception as e:
        _logger.debug(e)

    loop.call_later(5, task_push_spindles_status_to_cloud, loop)


def upload_main():

    loop = asyncio.new_event_loop()
    asyncio.set_event_loop(loop)

    loop.call_soon(task_push_spindles_status_to_cloud, loop)
    try:
        loop.run_forever()
    finally:
        loop.close()


if __name__ == "__main__":

    upload_main()